<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta 
    name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta 
    http-equiv="X-UA-Compatible" 
    content="ie=edge">
  <meta 
    name="theme-color" 
    content="#fff" 
    id="theme-color">
  <meta 
    name="description" 
    content="hexoDemo用于介绍如何使用hexo">
  <link 
    rel="icon" 
    href="/">
  <title>07-自定义按键修饰符&自定义指令</title>
  
    
      <meta 
        property="og:title" 
        content="07-自定义按键修饰符&amp;自定义指令">
    
    
      <meta 
        property="og:url" 
        content="https://zwl5670.gitee.io/2012/08/01/12-Vue%E5%9F%BA%E7%A1%80/07-%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6&amp;%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8C%87%E4%BB%A4/index.html">
    
    
      <meta 
        property="og:img" 
        content="https://img.songhn.com/img/Y67gdd.png">
    
    
      <meta 
        property="og:img" 
        content="hexoDemo用于介绍如何使用hexo">
    
    
      <meta 
        property="og:type" 
        content="article">
      <meta 
        property="og:article:published_time" 
        content="2012-08-01">
      <meta 
        property="og:article:modified_time" 
        content="2023-03-14">
      <meta 
        property="og:article:author" 
        content="zwl5670">
      
        
          <meta 
            property="og:article:tag" 
            content="Vue基础">
        
      
    
  
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  <link rel="preload" href="/css/main.css" as="style" >
  
  <link rel="modulepreload" href="//instant.page/5.1.0">
  
  <link rel="stylesheet" href="/css/main.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">
  
  
  
    <link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">
  
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
    function loadCSS(href, data, attr) {
      var sheet = document.createElement('link');
      sheet.ref = 'stylesheet';
      sheet.href = href;
      sheet.dataset[data] = attr;
      document.head.appendChild(sheet);
    }
    function changeCSS(cssFile, data, attr) {
      var oldlink = document.querySelector(data);
      var newlink = document.createElement("link");
      newlink.setAttribute("rel", "stylesheet");
      newlink.setAttribute("href", cssFile);
      newlink.dataset.prism = attr;
      document.head.replaceChild(newlink, oldlink);
    }
  </script>
  
    
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
  </script>
  
    <script>
      var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
        document.getElementById('theme-color').dataset.mode = getCssMediaQuery();
      }
    };
    setDarkmode();
    </script>
  
  
  
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
<meta name="generator" content="Hexo 6.3.0"></head>

  <body>
    <div class="wrapper">
       
      <nav class="navbar">
  <div class="navbar-logo">
    <a class="navbar-logo-main" href="/">
      
      <span class="navbar-logo-dsc">前端面试</span>
      </a>
  </div>
  <div class="navbar-menu">
    
      <a 
        href="/" 
        class="navbar-menu-item">
        
          首页
        
      </a>
    
      <a 
        href="/archives" 
        class="navbar-menu-item">
        
          归档
        
      </a>
    
      <a 
        href="/tags" 
        class="navbar-menu-item">
        
          标签
        
      </a>
    
      <a 
        href="/categories" 
        class="navbar-menu-item">
        
          分类
        
      </a>
    
      <a 
        href="/about" 
        class="navbar-menu-item">
        
          关于
        
      </a>
    
      <a 
        href="/links" 
        class="navbar-menu-item">
        
          友链
        
      </a>
    
    <button 
      class="navbar-menu-item darknavbar navbar-menu-btn" 
      aria-label="Toggle dark mode"
      id="dark">
      <i class="iconfont icon-weather"></i>
    </button>
    <button 
      class="navbar-menu-item searchnavbar navbar-menu-btn" 
      aria-label="Toggle search"
      id="search">
      <!-- <i 
        class="iconfont icon-search" 
        style="font-size: 1.2rem; font-weight: 400;">
      </i> -->
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img"
        class="iconify iconify--ion" width="28" height="28" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512">
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M256 80a176 176 0 1 0 176 176A176 176 0 0 0 256 80Z"></path>
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M232 160a72 72 0 1 0 72 72a72 72 0 0 0-72-72Z"></path>
        <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="28"
          d="M283.64 283.64L336 336"></path>
      </svg>
    </button>
  </div>
</nav> 
      
      <div 
        id="local-search" 
        style="display: none">
        <input
          class="navbar-menu-item"
          id="search-input"
          placeholder="请输入搜索内容..." />
        <div id="search-content"></div>
      </div>
      
      <div class="section-wrap">
        <div class="container">
          <div class="columns">
            <aside class="left-column">
              
              <div class="card card-author">
                
  <img 
    src="https://img.songhn.com/img/Y67gdd.png" 
    class="author-img"
    width="88"
    height="88"
    alt="author avatar">

<p class="author-name">zwl5670</p>
<p class="author-description">前端学习资料</p>
<div class="author-message">
  <a 
    class="author-posts-count" 
    href="/archives">
    <span>215</span>
    <span>文章</span>
  </a>
  <a 
    class="author-categories-count" 
    href="/categories">
    <span>14</span>
    <span>分类</span>
  </a>
  <a 
    class="author-tags-count" 
    href="/tags">
    <span>14</span>
    <span>标签</span>
  </a>
</div>

              </div>
               <div class="sticky-tablet">
  
  
    <article class="display-when-two-columns spacer">
      <div class="card card-content toc-card">
        <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#v-on%E7%9A%84%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="toc-text">v-on的按键修饰符</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Vue-%E5%86%85%E7%BD%AE%E7%9A%84%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="toc-text">Vue 内置的按键修饰符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%9A%84%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="toc-text">自定义的按键修饰符</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E6%8C%87%E4%BB%A4"><span class="toc-text">自定义全局指令</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E6%8C%87%E4%BB%A4%E7%9A%84%E4%B8%BE%E4%BE%8B1"><span class="toc-text">自定义全局指令的举例1</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E6%8C%87%E4%BB%A4%EF%BC%9A%E4%BD%BF%E7%94%A8%E9%92%A9%E5%AD%90%E5%87%BD%E6%95%B0%E7%9A%84%E7%AC%AC%E4%BA%8C%E4%B8%AAbinding%E5%8F%82%E6%95%B0%E6%8B%BF%E5%88%B0%E4%BC%A0%E9%80%92%E7%9A%84%E5%80%BC"><span class="toc-text">自定义全局指令：使用钩子函数的第二个binding参数拿到传递的值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%A7%81%E6%9C%89%E6%8C%87%E4%BB%A4"><span class="toc-text">自定义私有指令</span></a></li></ol>
      </div>
    </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header">
    <i 
      class="iconfont icon-fenlei" 
      style="padding-right: 2px;">
    </i>分类
  </div>
  <div class="categories-list">
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/">
        <div class="categories-list-item">
          前端工具
          <span class="categories-list-item-badge">13</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          CSS基础
          <span class="categories-list-item-badge">18</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          CSS进阶
          <span class="categories-list-item-badge">9</span>
        </div>
      </a>
    
      <a href="/categories/HTML/">
        <div class="categories-list-item">
          HTML
          <span class="categories-list-item-badge">12</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          JS基础
          <span class="categories-list-item-badge">56</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80ES6/">
        <div class="categories-list-item">
          JS基础ES6
          <span class="categories-list-item-badge">10</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/">
        <div class="categories-list-item">
          JS基础异步
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/JS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          JS进阶
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/%E7%A7%BB%E5%8A%A8web/">
        <div class="categories-list-item">
          移动web
          <span class="categories-list-item-badge">3</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%92%8CDOM/">
        <div class="categories-list-item">
          CSS和DOM
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/Node/">
        <div class="categories-list-item">
          Node
          <span class="categories-list-item-badge">16</span>
        </div>
      </a>
    
      <a href="/categories/Vue%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          Vue基础
          <span class="categories-list-item-badge">15</span>
        </div>
      </a>
    
      <a href="/categories/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">
        <div class="categories-list-item">
          性能优化
          <span class="categories-list-item-badge">7</span>
        </div>
      </a>
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/">
        <div class="categories-list-item">
          前端工程化
          <span class="categories-list-item-badge">8</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header">
    <i 
      class="iconfont icon-biaoqian" 
      style="padding-right: 2px;">
    </i>热门标签
  </div>
  <div class="tags-list">
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80/" 
        title="JS基础">
        <div class="tags-list-item">JS基础</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%9F%BA%E7%A1%80/" 
        title="CSS基础">
        <div class="tags-list-item">CSS基础</div>
      </a>
    
      <a 
        href="/tags/Node/" 
        title="Node">
        <div class="tags-list-item">Node</div>
      </a>
    
      <a 
        href="/tags/Vue%E5%9F%BA%E7%A1%80/" 
        title="Vue基础">
        <div class="tags-list-item">Vue基础</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/" 
        title="前端工具">
        <div class="tags-list-item">前端工具</div>
      </a>
    
      <a 
        href="/tags/HTML/" 
        title="HTML">
        <div class="tags-list-item">HTML</div>
      </a>
    
      <a 
        href="/tags/JS%E8%BF%9B%E9%98%B6/" 
        title="JS进阶">
        <div class="tags-list-item">JS进阶</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
        title="JS基础异步">
        <div class="tags-list-item">JS基础异步</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80ES6/" 
        title="JS基础ES6">
        <div class="tags-list-item">JS基础ES6</div>
      </a>
    
      <a 
        href="/tags/CSS%E8%BF%9B%E9%98%B6/" 
        title="CSS进阶">
        <div class="tags-list-item">CSS进阶</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" 
        title="前端工程化">
        <div class="tags-list-item">前端工程化</div>
      </a>
    
      <a 
        href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" 
        title="性能优化">
        <div class="tags-list-item">性能优化</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%92%8CDOM/" 
        title="CSS和DOM">
        <div class="tags-list-item">CSS和DOM</div>
      </a>
    
      <a 
        href="/tags/%E7%A7%BB%E5%8A%A8web/" 
        title="移动web">
        <div class="tags-list-item">移动web</div>
      </a>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
            <main class="main-column">
              
<article class="card card-content">
  <header>
    <h1 class="post-title">
      07-自定义按键修饰符&amp;自定义指令
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2012-07-31T16:00:00.000Z">
      <i 
        class="iconfont icon-calendar" 
        style="margin-right: 2px;">
      </i>
      <span>2012-08-01</span>
    </time>
    
      <span class="dot"></span>
      
        <a 
          href="/categories/Vue%E5%9F%BA%E7%A1%80/" 
          class="post-meta-link">
          Vue基础
        </a>
      
    
    
      <span class="dot"></span>
      <span>3k 字</span>
    
  </div>
  
    <div 
      class="post-meta post-show-meta" 
      style="margin-top: -10px;">
      <div style="display: flex; align-items: center;">
        <i 
          class="iconfont icon-biaoqian" 
          style="margin-right: 2px; font-size: 1.15rem;">
        </i>
        
          
          <a 
            href="/tags/Vue%E5%9F%BA%E7%A1%80/" 
            class="post-meta-link">
            Vue基础
          </a>
        
      </div>
    </div>
  
  </header>
  <div 
    id="section" 
    class="post-content">
    <p><ArticleTopAd></ArticleTopAd></p>
<h2 id="v-on的按键修饰符"><a href="#v-on的按键修饰符" class="headerlink" title="v-on的按键修饰符"></a>v-on的按键修饰符</h2><h3 id="Vue-内置的按键修饰符"><a href="#Vue-内置的按键修饰符" class="headerlink" title="Vue 内置的按键修饰符"></a>Vue 内置的按键修饰符</h3><p>通俗一点讲，指的是：监听键盘输入的事件。Vue 允许为 v-on 在监听键盘事件时添加按键修饰符。如下：</p>
<p>Vue内置的按键修饰符：</p>
<pre class="highlight"><span class="line">.enter</span><br><span class="line">.tab</span><br><span class="line">.delete (捕获 “删除” 和 “退格” 键)</span><br><span class="line">.esc</span><br><span class="line">.space</span><br><span class="line">.up</span><br><span class="line">.down</span><br><span class="line">.left</span><br><span class="line">.right</span><br><span class="line">1.0.8+版本：支持单字母的按键别名。</span><br></pre>


<p>比如说，<code>keyup</code>指的是：键盘（任何键位）抬起时的监听事件。<code>.enter</code>指的是：按enter键的按键修饰符。我们把这两个结合起来看看。</p>
<p><strong><code>@keyup.enter</code>举例</strong>：按enter键后的监听事件</p>
<p><code>@keyup.enter=&quot;addData&quot;</code>表示：按住enter键后，执行addData()方法。<strong>全称</strong>是<code>v-on:key.enter=&quot;addData&quot;</code>。</p>
<p>我们还是拿<code>01-04</code>这篇文章中的列表功能来举例。之前是点击“添加”按钮后，列表中会添加一个item。现在要求：在<strong>输入框</strong>中按enter键后，也能添加一个item。</p>
<p>核心代码如下：</p>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">v-model</span>=<span class="string">&quot;formData.name&quot;</span> @<span class="attr">keyup.enter</span>=<span class="string">&quot;addData&quot;</span>&gt;</span></span><br></pre>

<p>注意，如果写成<code>@keyup=&quot;addData&quot;</code>，效果却是：只要键盘的任何键位打了字（还没来得及按enter键），就会执行addData()方法，这种效果显然不是我们想要的。所以要加上修饰符<code>.enter</code>，表示只针对enter键。</p>
<h3 id="自定义的按键修饰符"><a href="#自定义的按键修饰符" class="headerlink" title="自定义的按键修饰符"></a>自定义的按键修饰符</h3><p>如果我们直接在代码的<code>&lt;input&gt;</code>标签里写<code>@keyup.f2=&quot;addData&quot;</code>，那么，按住「F2键」后，是没有效果的，因为「F2键」不是内置的按键修饰符（如果F2不能验证，你可以试一下F7）。</p>
<p>我们知道，每个按键都有一个键盘码。参考链接：</p>
<ul>
<li><a target="_blank" rel="noopener" href="http://www.cnblogs.com/wuhua1/p/6686237.html">js 里面的键盘事件对应的键码</a></li>
</ul>
<p>通过查阅，我们知道了「F2键」的键盘码为<code>113</code>，那代码可以这样写：（按住F2键后，执行 addData 方法）</p>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">v-model</span>=<span class="string">&quot;formData.name&quot;</span> @<span class="attr">keyup.113</span>=<span class="string">&quot;addData&quot;</span>&gt;</span></span><br></pre>

<p>虽然键盘码很全，但是不好记呀。于是，接下来，我们给键盘码定义别名。</p>
<p><strong>自定义全局按键修饰符</strong>：</p>
<pre class="highlight"><span class="line">//自定义全局按键修饰符</span><br><span class="line">Vue.config.keyCodes.f2 = 113;</span><br></pre>

<p>上方代码的书写位置，与自定义全局过滤器的位置，是并列的。</p>
<p>然后，我们就可以使用键盘码的别名了。</p>
<h2 id="自定义全局指令"><a href="#自定义全局指令" class="headerlink" title="自定义全局指令"></a>自定义全局指令</h2><h3 id="自定义全局指令的举例1"><a href="#自定义全局指令的举例1" class="headerlink" title="自定义全局指令的举例1"></a>自定义全局指令的举例1</h3><p><strong>举例1</strong>：让指定文本框自动获取焦点</p>
<p>如果我们想实现这个例子，原生js的写法是：</p>
<pre class="highlight"><span class="line"><span class="comment">//原生js写法：网页一打开，就让指定的输入框自动获取焦点</span></span><br><span class="line"><span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&#x27;search&#x27;</span>).<span class="title function_">focus</span>()</span><br></pre>

<p>代码的位置：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180527_2340.png" class="lozad post-image"src="http://img.smyhvae.com/20180527_2340.png"></p>
<p>但我们不建议这样做。我们可以通过Vue中的自定义指令来实现这个例子。步骤如下。</p>
<p>（1）使用<code>Vue.directive()</code>自定义全局指令：</p>
<pre class="highlight"><span class="line"></span><br><span class="line"><span class="comment">//自定义全局指令 v-focus：让文本框自动获取焦点</span></span><br><span class="line"><span class="comment">//参数1：指令的名称。注意，在定义的时候，指令的名称前面，不需要加 v- 前缀；但是：在`调用`的时候，必须在指令名称前 加上 v- 前缀</span></span><br><span class="line"><span class="comment">//参数2：是一个对象，这个对象身上，有一些指令相关的函数，这些函数可以在特定的阶段，执行相关的操作</span></span><br><span class="line"><span class="title class_">Vue</span>.<span class="title function_">directive</span>(<span class="string">&#x27;focus&#x27;</span>, &#123;</span><br><span class="line">	<span class="comment">//在每个函数中，第一个参数，永远是 el ，表示 被绑定了指令的那个元素，这个 el 参数，是一个原生的JS对象（DOM对象）</span></span><br><span class="line">    <span class="attr">bind</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123; <span class="comment">// 每当指令绑定到元素上的时候，会立即执行这个 bind 函数，【只执行一次】</span></span><br><span class="line">        <span class="comment">// 在元素 刚绑定了指令的时候，还没有 插入到 DOM中去，这时候，调用 focus 方法没有作用</span></span><br><span class="line">        <span class="comment">//  因为，一个元素，只有插入DOM之后，才能获取焦点</span></span><br><span class="line">        <span class="comment">// el.focus()</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">inserted</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123;  <span class="comment">// inserted 表示元素 插入到DOM中的时候，会执行 inserted 函数【触发1次】</span></span><br><span class="line">        el.<span class="title function_">focus</span>()</span><br><span class="line">        <span class="comment">// 和JS行为有关的操作，最好在 inserted 中去执行，放置 JS行为不生效</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">updated</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123;  <span class="comment">// 当VNode更新的时候，会执行 updated， 【可能会触发多次】</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre>

<p>上方的代码中，如果我们把<code>el.focus()</code>这行代码写在<code>bind</code>方法里，是没有效果的（但不会报错）。没有效果是因为，在执行到<code>bind</code>方法的时候，元素还没有插入到dom中去。</p>
<p>由此可以看看出：<code>bind</code>、<code>inserted</code>、<code>updated</code>这三个钩子函数的执行时机不同，且执行的次数有区别。</p>
<p>（2）在指定的文本框上加&#96;&#96;：</p>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">id</span>=<span class="string">&quot;search&quot;</span> <span class="attr">v-model</span>=<span class="string">&quot;keywords&quot;</span> <span class="attr">v-focus</span>&gt;</span></span><br></pre>

<p>完整版代码如下：</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;ie=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;vue2.5.16.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span></span><br><span class="line">        搜索框：</span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">id</span>=<span class="string">&quot;search&quot;</span> <span class="attr">v-model</span>=<span class="string">&quot;name&quot;</span> <span class="attr">v-focus</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//自定义全局指令 v-focus，让文本框自动获取焦点</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//参数1：指令的名称。注意，在定义的时候，指令的名称前面，不需要加 v- 前缀；但是：在`调用`的时候，必须在指令名称前 加上 v- 前缀</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//参数2：是一个对象，这个对象身上，有一些指令相关的函数，这些函数可以在特定的阶段，执行相关的操作</span></span></span><br><span class="line"><span class="language-javascript">        <span class="title class_">Vue</span>.<span class="title function_">directive</span>(<span class="string">&#x27;focus&#x27;</span>, &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//在每个函数中，第一个参数，永远是 el ，表示 被绑定了指令的那个元素，这个 el 参数，是一个原生的JS对象（DOM对象）</span></span></span><br><span class="line"><span class="language-javascript">            <span class="attr">bind</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123; <span class="comment">// 每当指令绑定到元素上的时候，会立即执行这个 bind 函数，【只执行一次】</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">// 在元素 刚绑定了指令的时候，还没有 插入到 DOM中去，这时候，调用 focus 方法没有作用</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//  因为，一个元素，只有插入DOM之后，才能获取焦点</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">// el.focus()</span></span></span><br><span class="line"><span class="language-javascript">            &#125;,</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">inserted</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123;  <span class="comment">// inserted 表示元素 插入到DOM中的时候，会执行 inserted 函数【触发1次】</span></span></span><br><span class="line"><span class="language-javascript">                el.<span class="title function_">focus</span>()</span></span><br><span class="line"><span class="language-javascript">                <span class="comment">// 和JS行为有关的操作，最好在 inserted 中去执行，防止 JS行为不生效</span></span></span><br><span class="line"><span class="language-javascript">            &#125;,</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">updated</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123;  <span class="comment">// 当VNode更新的时候，会执行 updated， 【可能会触发多次】</span></span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;)</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">new</span> <span class="title class_">Vue</span>(&#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">el</span>: <span class="string">&#x27;#app&#x27;</span>,</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">data</span>: &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="attr">name</span>: <span class="string">&#x27;smyhvae&#x27;</span></span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;)</span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br><span class="line"></span><br></pre>


<h3 id="自定义全局指令：使用钩子函数的第二个binding参数拿到传递的值"><a href="#自定义全局指令：使用钩子函数的第二个binding参数拿到传递的值" class="headerlink" title="自定义全局指令：使用钩子函数的第二个binding参数拿到传递的值"></a>自定义全局指令：使用钩子函数的第二个binding参数拿到传递的值</h3><p><strong>举例2</strong>：设置DOM元素的color样式</p>
<p>参考举例1中的写法，我们可能会这样给DOM元素设置样式：</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;ie=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;vue2.5.16.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span></span><br><span class="line">        搜索框：</span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">id</span>=<span class="string">&quot;search&quot;</span> <span class="attr">v-model</span>=<span class="string">&quot;name&quot;</span> <span class="attr">v-color</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//自定义全局指令 v-color：设置DOM元素的color属性</span></span></span><br><span class="line"><span class="language-javascript">        <span class="title class_">Vue</span>.<span class="title function_">directive</span>(<span class="string">&#x27;color&#x27;</span>, &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">bind</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123; <span class="comment">// 每当指令绑定到元素上的时候，会立即执行这个 bind 函数，【只执行一次】</span></span></span><br><span class="line"><span class="language-javascript">                el.<span class="property">style</span>.<span class="property">color</span> = <span class="string">&#x27;red&#x27;</span>;</span></span><br><span class="line"><span class="language-javascript">            &#125;,</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">inserted</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123;  <span class="comment">// inserted 表示元素 插入到DOM中的时候，会执行 inserted 函数【触发1次】</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">// 和JS行为有关的操作，最好在 inserted 中去执行，防止 JS行为不生效</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//el.focus()</span></span></span><br><span class="line"><span class="language-javascript">            &#125;,</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">updated</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123;  <span class="comment">// 当VNode更新的时候，会执行 updated， 【可能会触发多次】</span></span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;)</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">new</span> <span class="title class_">Vue</span>(&#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">el</span>: <span class="string">&#x27;#app&#x27;</span>,</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">data</span>: &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="attr">name</span>: <span class="string">&#x27;&#x27;</span></span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;)</span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>

<p>如上方代码所示，我们自定义了一个指令<code>v-color</code>，然后在<code>input</code>标签中用上了这个指令，就给元素设置了color属性。但是这个代码有个弊端是：color的属性值在定义指令的时候，被写死了。如何完善呢？我们可以在DOM元素中传参。一起来看看。</p>
<p>代码如下：【荐】</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;ie=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;vue2.5.16.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span></span><br><span class="line">        搜索框1：</span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">id</span>=<span class="string">&quot;search&quot;</span> <span class="attr">v-model</span>=<span class="string">&quot;name&quot;</span> <span class="attr">v-color</span>=<span class="string">&quot;&#x27;green&#x27;&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//自定义全局指令 v-color：设置DOM元素的color属性</span></span></span><br><span class="line"><span class="language-javascript">        <span class="title class_">Vue</span>.<span class="title function_">directive</span>(<span class="string">&#x27;color&#x27;</span>, &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="comment">// 样式，只要通过指令绑定给了元素，不管这个元素有没有被插入到页面中去，这个元素肯定有了一个内联的样式</span></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">// 将来元素肯定会显示到页面中，这时候，浏览器的渲染引擎必然会解析样式，应用给这个元素</span></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">// 意思是说，我们可以把样式的代码写到bind中去（即使这个时候，dom元素还没有被创建）</span></span></span><br><span class="line"><span class="language-javascript">            <span class="attr">bind</span>: <span class="keyword">function</span> (<span class="params">el, binding</span>) &#123; <span class="comment">// 每当指令绑定到元素上的时候，会立即执行这个 bind 函数，【只执行一次】</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">                <span class="variable language_">console</span>.<span class="title function_">log</span>(binding.<span class="property">name</span>); <span class="comment">//打印结果：color</span></span></span><br><span class="line"><span class="language-javascript">                <span class="variable language_">console</span>.<span class="title function_">log</span>(binding.<span class="property">value</span>); <span class="comment">//打印结果：green</span></span></span><br><span class="line"><span class="language-javascript">                <span class="variable language_">console</span>.<span class="title function_">log</span>(binding.<span class="property">expression</span>);  <span class="comment">//&#x27;green&#x27;</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">                el.<span class="property">style</span>.<span class="property">color</span> = binding.<span class="property">value</span><span class="comment">// 通过bining拿到v-color中传递过来的值</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">            &#125;,</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">inserted</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123;  <span class="comment">// inserted 表示元素 插入到DOM中的时候，会执行 inserted 函数【触发1次】</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">// 和JS行为有关的操作，最好在 inserted 中去执行，防止 JS行为不生效</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//el.focus()</span></span></span><br><span class="line"><span class="language-javascript">            &#125;,</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">updated</span>: <span class="keyword">function</span> (<span class="params">el</span>) &#123;  <span class="comment">// 当VNode更新的时候，会执行 updated， 【可能会触发多次】</span></span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;)</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">new</span> <span class="title class_">Vue</span>(&#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">el</span>: <span class="string">&#x27;#app&#x27;</span>,</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">data</span>: &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="attr">name</span>: <span class="string">&#x27;smyhvae&#x27;</span></span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;)</span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>

<p>上方代码中,bind方法里传递的第二个参数<code>binding</code>，可以拿到DOM元素中<code>v-color</code>里填的值。注意，<code>v-color=&quot;&#39;green&#39;&quot;</code>，这里面写的是字符串常量；如果去掉单引号，就成了变量，不是我们想要的。</p>
<p>效果：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180610_1323.png" class="lozad post-image"src="http://img.smyhvae.com/20180610_1323.png"></p>
<p><strong>自定义全局指令的简写形式</strong>：</p>
<p>在很多时候，你可能想在 bind 和 update 时触发相同行为，而不关心其它的钩子。比如上面的代码中，我们可以写成简写形式：</p>
<pre class="highlight"><span class="line"><span class="title class_">Vue</span>.<span class="title function_">directive</span>(<span class="string">&#x27;color&#x27;</span>, <span class="keyword">function</span> (<span class="params">el, binding</span>) &#123; <span class="comment">//注意，这个function等同于把代码写到了 bind 和 update 中去</span></span><br><span class="line">    el.<span class="property">style</span>.<span class="property">color</span> = binding.<span class="property">value</span></span><br><span class="line">&#125;)</span><br></pre>


<h2 id="自定义私有指令"><a href="#自定义私有指令" class="headerlink" title="自定义私有指令"></a>自定义私有指令</h2><p><strong>自定义私有指令</strong>：在某一个 vue 对象内部自定义的指令称之为私有指令。这种指令只有在当前vue对象的el指定的监管区域有用。</p>
<p>代码举例：（设置文字的font-weight属性）</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;ie=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;vue2.5.16.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">span</span> <span class="attr">v-fontweight</span>=<span class="string">&quot;600&quot;</span>&gt;</span>生命壹号<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">new</span> <span class="title class_">Vue</span>(&#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">el</span>: <span class="string">&#x27;#app&#x27;</span>,</span></span><br><span class="line"><span class="language-javascript">            <span class="attr">data</span>: &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="attr">name</span>: <span class="string">&#x27;smyhvae&#x27;</span></span></span><br><span class="line"><span class="language-javascript">            &#125;,</span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//自定义私有指令</span></span></span><br><span class="line"><span class="language-javascript">            <span class="attr">directives</span>: &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="string">&#x27;fontweight&#x27;</span>: &#123;</span></span><br><span class="line"><span class="language-javascript">                    <span class="attr">bind</span>: <span class="keyword">function</span> (<span class="params">el, binding</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                        el.<span class="property">style</span>.<span class="property">fontWeight</span> = binding.<span class="property">value</span>;</span></span><br><span class="line"><span class="language-javascript">                    &#125;</span></span><br><span class="line"><span class="language-javascript">                &#125;</span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;)</span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>

<p>效果：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180610_1400.png" class="lozad post-image"src="http://img.smyhvae.com/20180610_1400.png"></p>
<p>注意， el.style.fontWeight设置属性值，至少要600，否则看不到加粗的效果。</p>
<p><strong>自定义私有指令的简写形式</strong>：</p>
<p>在很多时候，你可能想在 bind 和 update 时触发相同行为，而不关心其它的钩子。比如上面的代码中，我们可以写成简写形式：</p>
<pre class="highlight"><span class="line">//自定义私有指令（简写形式）</span><br><span class="line">directives: &#123;</span><br><span class="line">    &#x27;fontweight&#x27;: function (el, binding) &#123; //注意，这个function等同于把代码写到了 bind 和 update 中去</span><br><span class="line">        el.style.fontWeight = binding.value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre>








  </div>
  <div>
    
      <div 
        class="post-note note-warning copyright" 
        style="margin-top: 42px">
        <p>
          <span style="font-weight: bold;">作者：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="/about">
            zwl5670
          </a>
        </p>
        <p>
          <span style="font-weight: bold;">文章链接：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="https://zwl5670.gitee.io/2012/08/01/12-Vue%E5%9F%BA%E7%A1%80/07-%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6&amp;%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8C%87%E4%BB%A4/">
            https://zwl5670.gitee.io/2012/08/01/12-Vue%E5%9F%BA%E7%A1%80/07-%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6&amp;%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8C%87%E4%BB%A4/
          </a>
        </p>
        <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
      </div>
    
  </div>
</article>
<div class="nav">
  
    <div class="nav-item-prev">
      <a 
        href="/2012/08/01/12-Vue%E5%9F%BA%E7%A1%80/08-Vue%E5%AE%9E%E4%BE%8B%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%87%BD%E6%95%B0/" 
        class="nav-link">
        <i class="iconfont icon-left nav-prev-icon"></i>
        <div>
          <div class="nav-label">上一篇</div>
          
            <div class="nav-title">08-Vue实例的生命周期函数 </div>
          
        </div>
      </a>
    </div>
  
  
    <div class="nav-item-next">
      <a 
        href="/2012/08/01/12-Vue%E5%9F%BA%E7%A1%80/09-Vue%E4%B8%AD%E7%9A%84Ajax%E8%AF%B7%E6%B1%82/" 
        class="nav-link">
        <div>
          <div class="nav-label">下一篇</div>
          
            <div class="nav-title">09-Vue中的Ajax请求 </div>
          
        </div>
        <i class="iconfont icon-right nav-next-icon"></i>
      </a>
    </div>
  
</div>

<div 
  class="card card-content toc-card" 
  id="mobiletoc">
  <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#v-on%E7%9A%84%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="toc-text">v-on的按键修饰符</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Vue-%E5%86%85%E7%BD%AE%E7%9A%84%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="toc-text">Vue 内置的按键修饰符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%9A%84%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="toc-text">自定义的按键修饰符</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E6%8C%87%E4%BB%A4"><span class="toc-text">自定义全局指令</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E6%8C%87%E4%BB%A4%E7%9A%84%E4%B8%BE%E4%BE%8B1"><span class="toc-text">自定义全局指令的举例1</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E6%8C%87%E4%BB%A4%EF%BC%9A%E4%BD%BF%E7%94%A8%E9%92%A9%E5%AD%90%E5%87%BD%E6%95%B0%E7%9A%84%E7%AC%AC%E4%BA%8C%E4%B8%AAbinding%E5%8F%82%E6%95%B0%E6%8B%BF%E5%88%B0%E4%BC%A0%E9%80%92%E7%9A%84%E5%80%BC"><span class="toc-text">自定义全局指令：使用钩子函数的第二个binding参数拿到传递的值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%A7%81%E6%9C%89%E6%8C%87%E4%BB%A4"><span class="toc-text">自定义私有指令</span></a></li></ol>
</div>
            </main>
            <aside class="right-column">
              <div class="sticky-widescreen">
  
  
    <article class="card card-content toc-card">
      <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#v-on%E7%9A%84%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="toc-text">v-on的按键修饰符</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Vue-%E5%86%85%E7%BD%AE%E7%9A%84%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="toc-text">Vue 内置的按键修饰符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%9A%84%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="toc-text">自定义的按键修饰符</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E6%8C%87%E4%BB%A4"><span class="toc-text">自定义全局指令</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E6%8C%87%E4%BB%A4%E7%9A%84%E4%B8%BE%E4%BE%8B1"><span class="toc-text">自定义全局指令的举例1</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%A8%E5%B1%80%E6%8C%87%E4%BB%A4%EF%BC%9A%E4%BD%BF%E7%94%A8%E9%92%A9%E5%AD%90%E5%87%BD%E6%95%B0%E7%9A%84%E7%AC%AC%E4%BA%8C%E4%B8%AAbinding%E5%8F%82%E6%95%B0%E6%8B%BF%E5%88%B0%E4%BC%A0%E9%80%92%E7%9A%84%E5%80%BC"><span class="toc-text">自定义全局指令：使用钩子函数的第二个binding参数拿到传递的值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%A7%81%E6%9C%89%E6%8C%87%E4%BB%A4"><span class="toc-text">自定义私有指令</span></a></li></ol>
    </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header">
    <i 
      class="iconfont icon-wenzhang_huaban" 
      style="padding-right: 2px;">
    </i>最近文章
  </div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/11-React%20Navive%E5%88%9D%E8%AF%86/"><div class="recent-posts-item-content">11-React Navive初识</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/10-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E4%BD%BF%E7%94%A8customRequest%E6%96%B9%E6%B3%95%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%8A%E4%BC%A0%E8%A1%8C%E4%B8%BA/"><div class="recent-posts-item-content">10-AntD框架的upload组件上传图片时使用customRequest方法自定义上传行为</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/09-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E9%81%87%E5%88%B0%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91/"><div class="recent-posts-item-content">09-AntD框架的upload组件上传图片时遇到的一些坑</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/08-Ant%20Design%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/"><div class="recent-posts-item-content">08-Ant Design的基本使用</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
          </div>
        </div>
      </div>
    </div>
     
    <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>
          Copyright ©
          
            2023
          
          
        </span>
        &nbsp;
        <a 
          href="/" 
          class="footer-link">
          前端面试
        </a>
      </div>
    </div>

    
      <div class="footer-dsc">
        
          Powered by
          <a 
            href="https://hexo.io/" 
            class="footer-link" 
            target="_blank" 
            rel="nofollow noopener noreferrer">
            &nbsp;Hexo
          </a>
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          Theme -
          <a 
            href="https://github.com/theme-kaze" 
            class="footer-link" 
            target="_blank"
            rel="nofollow noopener noreferrer">
            &nbsp;Kaze
          </a>
        
      </div>
    
    
    
    
</footer>
 
    
  <a 
    role="button" 
    id="scrollbutton" 
    class="basebutton" 
    aria-label="回到顶部">
    <i class="iconfont icon-arrowleft button-icon"></i>
  </a>

<a 
  role="button" 
  id="menubutton"
  aria-label="menu button"
  class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a 
  role="button" 
  id="popbutton" 
  class="basebutton" 
  aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a 
  role="button" 
  id="darkbutton" 
  class="basebutton darkwidget" 
  aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a 
  role="button" 
  id="searchbutton" 
  class="basebutton searchwidget" 
  aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a> 
     
     
     
      <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img')
    var i
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a')
      wrapper.setAttribute('href', img[i].getAttribute('data-src'))
      wrapper.setAttribute('aria-label', 'illustration')
      wrapper.style.cssText =
        'width: 100%; display: flex; justify-content: center;'
      if (img[i].alt) wrapper.dataset.caption = img[i].alt
      wrapper.dataset.nolink = true
      img[i].before(wrapper)
      wrapper.append(img[i])
      var divWrap = document.createElement('div')
      divWrap.classList.add('gallery')
      wrapper.before(divWrap)
      divWrap.append(wrapper)
    }
    baguetteBox.run('.gallery')
  }
</script>
<script>
  loadScript(
    "/js/lib/lightbox/baguetteBox.min.js",
    addImgLayout
  )
</script>
 
     
     
    <script src="/js/main.js"></script> 
     
    
      <script>
        var addLazyload = function () {
          var observer = lozad('.lozad', {
            load: function (el) {
              el.srcset = el.getAttribute('data-src')
            },
            loaded: function (el) {
              el.classList.add('loaded')
            },
          })
          observer.observe()
        }
      </script>
      <script>
        loadScript('/js/lib/lozad.min.js', addLazyload)
      </script>
    
    <script src="//instant.page/5.1.0" type="module"
      integrity="sha384-by67kQnR+pyfy8yWP4kPO12fHKRLHZPfEsiSXR8u2IKcTdxD805MGUXBzVPnkLHw"></script>
    
    
  </body>
</html>
